#include "prec.h"
#include "artpanel.h"
#include "wx/log.h"
#include "wx/dcbuffer.h"

IMPLEMENT_DYNAMIC_CLASS(ArtPanel, wxPanel)

BEGIN_EVENT_TABLE(ArtPanel, wxPanel)
	EVT_PAINT(ArtPanel::OnPaint)
	EVT_SIZE(ArtPanel::OnSize)
END_EVENT_TABLE()

ArtPanel::ArtPanel( wxWindow *parent, wxWindowID winid, 
				   const wxBitmap& bitmap, 
				   const wxPoint& pos, 
				   const wxSize& size, 
				   long style, 
				   long artstyle, 
				   const wxString& name )
				   : wxPanel(parent, winid, pos, size, style, name)
				   , m_artStyle(artstyle)
				   , m_groundBitmap(bitmap)
{
	m_painted = false;
	m_size = wxSize(20,20);
	m_bitmap = new wxBitmap(m_size.x, m_size.y);
}

ArtPanel::~ArtPanel()
{
	delete m_bitmap;
}

void ArtPanel::OnPaint( wxPaintEvent& event )
{
	wxPaintDC dc(this);
	dc.DrawBitmap(*m_bitmap,0,0,false);
}

void ArtPanel::OnSize( wxSizeEvent& event )
{
	m_size = event.GetSize();
	DrawOnBitmap();
	event.Skip();
}

wxBitmap ArtPanel::GetBackgroundRegion( wxWindowID childId )
{
	wxWindow* win = FindWindow(childId);
	if(m_painted && win) {
		int x,y,w,h;
		win->GetSize(&w,&h);
		win->GetPosition(&x,&y);
		// background clipping
		wxRect r = GetRect();
		int dx = (r.x + r.width) - x;
		if(dx < w) w = dx;
		if(w > 0) return m_bitmap->GetSubBitmap(wxRect(x,y,w,h));
	}
	return wxNullBitmap;
}

void ArtPanel::Redraw()
{
	wxClientDC dc(this);
	DrawOnBitmap();
	dc.DrawBitmap(*m_bitmap,0,0,false);
}

void ArtPanel::DrawOnBitmap()
{
	if((m_bitmap->GetWidth() != m_size.x) || 
		(m_bitmap->GetHeight() != m_size.y)) {
			m_bitmap->Create(m_size.x,m_size.y);
			m_painted = true;
	}

	wxMemoryDC dc;
	dc.SelectObject(*m_bitmap);

	wxBrush brush(GetBackgroundColour(), wxSOLID);
	dc.SetBackground(brush);
	dc.Clear();

	if (m_groundBitmap.Ok())
	{
		int gx = 0, gy = 0;

		if (m_artStyle & BITMAP_STRETCH)
		{
			if (m_size.x > 0 && m_size.y > 0)
			{
				wxImage image = m_groundBitmap.ConvertToImage();
				image.Rescale(m_size.x, m_size.y);
				dc.DrawBitmap(image,  0,  0, false);
			}
		}
		else
		{
			if (m_artStyle & BITMAP_CETER)
			{
				gx = (m_size.x - m_groundBitmap.GetWidth())/2;
				gy = (m_size.y - m_groundBitmap.GetHeight())/2;
			}
			dc.DrawBitmap(m_groundBitmap, gx, gy, false);
		}
	}

	dc.SelectObject(wxNullBitmap);
}